<template>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="close" width="70%" :close-on-click-modal="false">
        <el-form ref="form" :model="form" :site="site" label-width="105px">
            <el-form-item label="当前经度" prop="lng" style="width: 300px; float:left;">
                <el-input v-model="form.lng" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item class="lat" label="当前纬度" prop="lng" style="width: 300px; float:left;">
                <el-input v-model="form.lat" autocomplete="off"></el-input>
            </el-form-item>
            <div class="el-form-item area el-form-item--medium" style="width: 300px;float:left;margin: 0;">
                <city-area :clearable="true" :areaSelected="areaSelected" :defaultProps="areaProps"
                           @area-change="listenArea"></city-area>
            </div>
            <el-form-item label="站点片区" prop="site_area_id">
                <el-select filterable v-model="form.site_area_id" placeholder="请选择站点片区"
                           clearable size="small" style="width: 240px">
                    <el-option v-for="dict in siteAreaOptions" :key="dict.id" :label="dict.title" :value="dict.id"/>
                </el-select>
            </el-form-item>
            <div class="el-form-item search el-form-item--medium">
                <div class="el-form-item__content">
                    <div class="el-input el-input--medium">
                        <input type="text" autocomplete="off" v-model="keyWords" placeholder="请输入要搜索的地址" class="el-input__inner"
                               style=" float: left;">
                        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="setPlace"></el-button>
                    </div>
                    <div class="panel" id="panel_ul" style="height: 366px;overflow-x: scroll;">
                        <div v-for="(item, index) in mapAllPoisList" class="poi" :key="index"
                             style="cursor: pointer;line-height: 32px;height: 32px;font-size: 13px" @click="poiClick(item,index)">
                            <p style="margin: 0 0 0 8px !important; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;"
                               poiid="" :title="item.address">
                                <span class="sug_val">{{index+1}}.{{item.title}}</span>
                                <span style="margin-left: 10px;margin-right: 5px;color: #999;font-size: 12px" class="district">{{item.address}}</span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </el-form>
        <div id="container" :id="mapId" class="map-area"></div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
        </div>
    </el-dialog>

</template>

<script type="text/javascript">
import { loadBdMap as loadBMap } from '@/api/tool/loadBMap'
import { getSelectLists as getSiteAreaSelectLists } from '@/api/admin/system/site/area'
import CityArea from '@/components/CityArea'

export default {
    name: 'baidumap',
    components: { CityArea },
    props: [
        'areaMap'
    ],
    data() {
        return {
            title: '',
            dialogFormVisible: false,
            ak: 'exr110xo0sNiGM1swXWhqVZix17T2xT6',
            mapId: 'BMap-allmap',
            map: null,//地图实例
            mk: null, //Marker实例
            myGeo: null,
            localSearch: null,
            map_label: null,
            mapAllPoisList: [],
            zoom: 13,
            point: '',
            keyWords: '中国石化济南',
            form: {
                district_id: 0
            },
            areaProps: {
                children: '_child',
                label: 'name',
                value: 'id'
            },

            areaSelected: {},
            siteAreaOptions: {},
            panel_ul: '',
            area_name: '山东省'

        }
    },
    created: async function() {
        console.log('加载...............')
    },
    mounted() {
        console.log('mounted ...............')
    },
    methods: {
        //自定义监听方法
        listenArea(selectedOptions, val, obj) {
            console.log('selectedOptions', selectedOptions)
            console.log('selectedOptions-val--', val)
            console.log('selectedOptions-obj--', obj)
            this.form.province_id = selectedOptions[0]
            this.form.city_id = selectedOptions[1]
            this.form.district_id = selectedOptions[2]
            this.area_name = obj[0].pathLabels[0] + obj[0].pathLabels[1] + obj[0].pathLabels[2]
            this.handleTreeNodeClick(selectedOptions)
        },
        /** */
        async areaChange(val){
            this.form.province_id = val[0]
            this.form.city_id = val[1]
            this.form.district_id = val[2]
            this.handleTreeNodeClick(val)
        },
        async handleTreeNodeClick(selected) {
            const { data } = await getSiteAreaSelectLists({
                province_id: selected[0],
                city_id: selected[1],
                district_id: selected[2]
            })
            if (data) {
                this.is_site_area = 1
                this.siteAreaOptions = data
            }
        },

        initBaiduMap() {
            loadBMap(this.ak).then((loadBMap) => {
                var _that = this
                // 创建地图实例
                _that.map = new BMap.Map(this.mapId)
                // 创建点坐标 axios => res 获取的初始化定位坐标
                _that.point = new BMap.Point(this.form.lng, this.form.lat)
                // // 初始化地图，设置中心点坐标和地图级别
                _that.map.centerAndZoom(_that.point, _that.zoom)
                //添加地图类型控件
                _that.map.addControl(new BMapGL.MapTypeControl({
                    mapTypes: [
                        BMAP_NORMAL_MAP,
                        BMAP_HYBRID_MAP
                    ]
                }))

                console.log(_that.area_name)
                // 设置地图显示的城市 此项是必须设置的
                // _that.map.setCurrentCity(_that.area_name);

                //开启鼠标滚轮缩放
                _that.map.enableScrollWheelZoom(true)
                // this.myMap.setHeading(64.5)
                // this.myMap.setTilt(73)

                //创建地址解析器实例
                _that.myGeo = new BMapGL.Geocoder()
                // 将地址解析结果显示在地图上，并调整地图视野
                _that.myGeo.getPoint(this.keyWords, function(point) {
                    if (point) {
                        _that.map.centerAndZoom(point, _that.zoom)
                        _that.map.addOverlay(new BMapGL.Marker(point, { title: _that.keyWords }))
                    } else {
                        console.log('您选择的地址没有解析到结果！')
                    }
                })
            }).catch((err) => {
                console.log(err)
            })
        },

        // 搜索地址
        setPlace() {
            //查询参数
            var _that = this
            var ResultArray = [];
            _that.localSearch = new BMap.LocalSearch(_that.map, {
                renderOptions: {
                    map: _that.map
                }, onMarkersSet: function(array) {
                    // console.log("onMarkersSet-",array);
                },
                onInfoHtmlSet: function(LocalResultPoi) {
                    // console.log("LocalResultPoi-",LocalResultPoi);
                },
                onResultsHtmlSet: function(element) {
                    console.log('element', element)
                },
                onSearchComplete: function(results) {
                    console.log('执行顺序-', 1)
                    console.log('results-', results)
                    if (results) {


                        // 需要获取当前搜索总共有多少条结果
                        var totalPages = results.getNumPages()
                        // 获取当前是第几页数据
                        var currPage = results.getPageIndex()
                        console.log('totalPages---', totalPages)
                        console.log('currPage---', currPage)
                        if (currPage < totalPages - 1) {
                            console.log('getCurrentNumPois---', results.getCurrentNumPois())

                            console.log(results.getCurrentNumPois())
                            console.log('_that.localSearch.getResults().Br', _that.localSearch.getResults().Br)

                            var pois = results._pois
                            ResultArray.push(...pois)
                            // _that.mapAllPoisList.push(...pois);
                            console.log('pois-', pois)
                            // 遍历到最后一页之后不再进行下一页搜索，此时，已经获取到全部的搜索结果，
                            _that.localSearch.gotoPage(currPage + 1)

                            console.log(_that.localSearch.getResults())
                        } else {
                            // 已经到达最后一页结果
                            _that.map.clearOverlays() //清除地图上所有覆盖物
                            var pois = results._pois
                            ResultArray.push(...pois)
                            // _that.mapAllPoisList.push(...pois);

                            _that.point = _that.localSearch.getResults().getPoi(0).point
                            _that.map.enableScrollWheelZoom(true)
                            _that.map.centerAndZoom(_that.point, 13)

                            console.log('全部结果有：' + ResultArray.length + '------原本搜索结果有：' + results.getNumPois())
                        }
                        _that.mapAllPoisList = ResultArray
                    }
                },
                pageCapacity: 50
            })
            _that.mapAllPoisList = ResultArray;
            this.localSearch.search(this.keyWords)
            this.localSearch.searchNearby(['加油站'])
        },
        handleMarker(points, infoWindows, obj) {
            obj.mk = new BMapGL.Marker(points)
            obj.map.addOverlay(this.mk) // 将标注添加到地图中
            obj.mk.setLabel(obj.map_label) // 将data中的name添加到地图中
            // 标注的点击事件
            obj.mk.addEventListener('click', function(event) {
                console.log('187-event-:', event)
                console.log('187-points-:', points)
                obj.form.lng = points.lng
                obj.form.lat = points.lat
                obj.map.openInfoWindow(infoWindows, points)//参数：窗口、点  根据点击的点出现对应的窗口
            })
        },

        poiClick(obj, i) {
            this.addsite(obj)
            console.log(obj.title, obj.address, obj.point.lng, obj.point.lat)
            var _that = this
            // 创建信息窗口对象
            var content = '<div style="margin:0;line-height:20px;padding:2px;">' +
                '<p>地址：' + obj.address + '</p>' +
                '<p>电话：' + obj.phoneNumber + '</p>' +
                '<p>经纬度：' + obj.point.lng + '-- ' + obj.point.lat + '</p>' +
                '</div>'

            let infoWindow = new BMapGL.InfoWindow(content, {
                width: 400,    // 信息窗口宽度
                height: 130,    // 信息窗口高度
                panel: 'panel', //检索结果面板
                title: obj.title // 信息窗口标题
            })
            // 将data中的name加入地图中allPois[i].title
            _that.map_label = new BMapGL.Label(i + 1, {
                offset: new BMapGL.Size(-7, -21)
            })
            _that.map_label.setStyle({
                background: 'none', color: '#fff', border: '0', width: 10
            })
            // _that.handleMarker(obj.point, infoWindow, _that)
            _that.mk = new BMapGL.Marker(obj.point)
            _that.map.addOverlay(_that.mk) // 将标注添加到地图中
            _that.mk.setLabel(_that.map_label) // 将data中的name添加到地图中
            // 标注的点击事件
            _that.mk.addEventListener('click', function(event) {
                console.log('187-event-:', event)
                console.log('187-points-:', obj.point)
                _that.form.lng = obj.point.lng
                _that.form.lat = obj.point.lat
                // var searchInfoWindow3 = new BMapLib.SearchInfoWindow(_that.map, content, {
                //     title: obj.title, //标题
                //     width: 290, //宽度
                //     height: 110, //高度
                //     panel : "panel", //检索结果面板
                //     enableAutoPan : true, //自动平移
                //
                // });
                // searchInfoWindow3.open(new BMapGL.Point(obj.point.lng,obj.point.lat));
                _that.map.openInfoWindow(infoWindow, obj.point)//参数：窗口、点  根据点击的点出现对应的窗口
            })

            _that.point = _that.localSearch.getResults().getPoi(0).point
            _that.map.enableScrollWheelZoom(true)
            _that.map.centerAndZoom(obj.point, 17)
            console.log('经度：' + _that.point.lng + '--' + '纬度' + _that.point.lat)
        },
        addsite(obj) {
            this.form.site_name = obj.title
            this.form.site_address = obj.address
            this.form.site_phone = obj.phoneNumber
            this.form.lng = obj.point.lng
            this.form.lat = obj.point.lat
            console.log("列表",this.form)
            //this.$post(this.$api.adminSite + '/updatemap', this.form)
        },
        // 表单重置
        reset() {
            this.form = {
                site_name: null,
                site_address: null,
                site_phone: null,
                province_id: 0,
                district_id: 0,
                lng: 117.1154,
                lat: 36.6695
            }
            this.resetForm('form')
        },

        showEdit(row) {
            this.reset()
            this.title = ''
            this.keyWords = ''
            this.title = '站点信息：（' + row.site_name + '）'
            this.form = Object.assign({}, row)
            this.dialogFormVisible = true
            this.keyWords = this.form.site_address
            console.log(this.form)
            this.initBaiduMap()
        },
        close() {
            this.$refs['form'].resetFields()
            this.form = this.$options.data().form
            this.dialogFormVisible = false
        },
        save() {
            console.log("this.form",this.form)
           /* this.$refs['form'].validate(async(valid) => {
                if (valid) {
                    console.log(this.form)
                    const { msg, status } = await this.$put(this.$api.adminSite + this.$api.update, this.form)
                    //
                    switch (status) {
                        case 1:
                            this.$message({
                                message: msg,
                                type: 'success'
                            })

                            this.$emit('fetchData')
                            this.close()
                            break
                        default:
                            this.$message({
                                message: msg,
                                type: 'error'
                            })
                            break
                    }
                } else {
                    return false
                }
            })*/
        }
    }
}
</script>

<style lang="scss" scoped>
.map-area {
    width: 100%;
    height: 405px;
}

.area {
    .el-form-item__content {
        margin-left: 50px !important;
    }
}

.search {
    width: 323px;
    float: left;
    margin: 0;
    position: relative;

    .el-input {
        display: flex;
    }

    .panel {
        /*width: 323px;*/
        position: absolute;
        z-index: 1001;
        /*left: 0px;*/
        /*right: 0px;*/
        /*top: 36px;*/
        /*background: rgb(255, 255, 255);*/
        /*border: 1px solid red;*/
        /*height: 200px;*/
        /*overflow-y: auto;*/
        margin-top: -5px;
        background: #fff;
        top: 45px;
        left: 0;
        border: none;
        border-top: 1px solid #E4E6E7;
        box-shadow: 1px 2px 1px rgb(0 0 0 / 15%);
        border-radius: 0 0 2px 2px;
        max-width: 360px;

        .poi {
            background-color: #fff;
            white-space: nowrap;
            height: 32px;
            line-height: 32px;
            cursor: pointer;
            background-repeat: no-repeat;
            background-size: 40px;
            font-size: 13px;
            overflow: hidden;
            color: #404040;

            p {
                margin-left: 32px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;

                .district {
                    margin-left: 10px;
                    margin-right: 5px;
                    color: #999;
                    font-size: 12px;
                }
            }
        }
    }

}


</style>
